<template>
  <view v-if="!loading">
    <view>
      <u-tabs-swiper
        ref="uTabs"
        :list="list"
        :current="current"
        @change="tabsChange"
        :is-scroll="false"
        swiperWidth="750"
      ></u-tabs-swiper>
    </view>
    <swiper
      :class="[
        'swiper',
        {
          noButton: !(
            taskInfo.approvalPermission || taskInfo.urgeSignPermission === 1
          ),
        },
      ]"
      :current="swiperCurrent"
      @transition="transition"
      @animationfinish="animationfinish"
    >
      <swiper-item
        class="swiper-item"
        v-for="(item, index) in list"
        :key="index"
      >
        <scroll-view
          scroll-y
          class="content-page"
          :style="`width: 100%`"
          @scrolltolower="onreachBottom"
        >
          <template v-for="(el, i) in taskInfo.formList">
            <view v-if="list[0].name === item.name" class="transition-bg">
              <view>
                <view class="u-line-2 project-name">
                  {{ taskInfo.projectName }}
                </view>
                <view class="tag-box">
                  <view>
                    <text class="tag-item">
                      {{ taskInfo.projectTypeName }}-{{
                        taskInfo.registerTypeName
                      }}
                    </text>
                    <text class="tag-item m-x-10">{{
                      taskInfo.stagesName
                    }}</text>
                    <text class="tag-item">{{ projectInfo.projectNo }}</text>
                  </view>
                </view>
                <view class="u-m-t-20">
                  <describeVue
                    :data="taskInfo"
                    :column="headColumn"
                    :empty-value="'无'"
                  ></describeVue>
                </view>
                <view class="u-m-t-10 u-m-b-10">
                  <u-divider
                    border-color="#e8eaee"
                    half-width="50%"
                    :use-slot="false"
                  ></u-divider>
                </view>
                <view class="u-text-right">
                  <span
                    class="font-bold"
                    :class="TASK_STATUS_TYPES_MAP[taskInfo.taskStatus]?.color"
                    >{{
                      TASK_STATUS_TYPES_MAP[taskInfo.taskStatus]?.label
                    }}</span
                  >
                </view>
              </view>
            </view>
            <customFormRender
              v-if="
                list[swiperCurrent].name === el.formName &&
                swiperCurrent === index
              "
              :query-value-flag="1"
              :form-id="el.formId"
            />
          </template>
          <fileList
            ref="refFileList"
            v-if="
              list[swiperCurrent].name === '文件信息' && swiperCurrent === index
            "
            :taskInfo="taskInfo"
          ></fileList>
        </scroll-view>
      </swiper-item>
    </swiper>
    <view
      v-if="taskInfo.approvalPermission || taskInfo.urgeSignPermission === 1"
      class="btn-box u-flex u-row-between fileList-sign-btn"
    >
      <u-button
        :class="[taskInfo.approvalPermission ? 'urge-sign' : '']"
        v-if="taskInfo.urgeSignPermission === 1"
        :style="{ flex: taskInfo.approvalPermission ? 0 : 1 }"
        shape="circle"
        type="primary"
        plain
        :loading="urgeSignLoading"
        @click="expeditingSign"
        >催签</u-button
      >
      <u-button
        v-if="taskInfo.approvalPermission"
        shape="circle"
        type="primary"
        @click="gotoApproval"
        >{{ taskInfo.taskStatus === 8 ? '受理' : '审批' }}</u-button
      >
    </view>
  </view>
  <projectApplicationSkeleton v-if="loading"></projectApplicationSkeleton>
</template>
<script lang="ts" setup>
// import { TaskStatusEnum } from '../index';
import { onLoad } from '@dcloudio/uni-app';
import fileList from '@/components/fileList/index.vue';
import { queryProjectApplyDetail } from '@/api/modules/home';
import { TASK_STATUS_TYPES_MAP } from '@/pageProject/project/work/index';
import describeVue from '@/components/describe.vue';
import { useBack } from '@/hooks/useBack';
import customFormRender from '@/components/customFormRender/index.vue';
import projectApplicationSkeleton from './projectApplicationSkeleton.vue';
import { urgeSign } from '@/api/modules/signFile';
const list = ref<any[]>([]);
const headColumn = [
  {
    label: '申请人',
    prop: 'applyUserName',
    width: 200,
  },
  {
    label: '申请时间',
    prop: 'applyTime',
    width: 200,
  },
  {
    label: '当前经办人',
    prop: 'approvalParamValue',
    width: 200,
  },
];
// const taskInfo = ref<any>({ viewPermission: false, memberList: [] });
const taskFileInfo = ref<any>({});
const spinning = ref(true);
const current = ref(0);
const swiperCurrent = ref(0);

const tabsChange = (index: number) => {
  swiperCurrent.value = index;
};
// swiper-item左右移动，通知tabs的滑块跟随移动
const uTabs = ref();
const transition = (e: any) => {
  let dx = e.detail.dx;
  uTabs.value.setDx(dx);
};
// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
// swiper滑动结束，分别设置tabs和swiper的状态
const animationfinish = (e: any) => {
  let curr = e.detail.current;
  uTabs.value.setFinishCurrent(curr);
  swiperCurrent.value = curr;
  current.value = curr;
};

const onreachBottom = () => {};

const gotoApproval = () => {
  (uni as any).$Router.push({
    name: 'approval',
    params: {
      id: taskInfo.value.taskId,
      taskType: taskInfo.value.taskType,
      supplementFile:
        taskInfo.value.taskType === 3 && taskFileInfo.value.taskStatus === 4
          ? true
          : undefined,
    },
  });
};
const urgeSignLoading = ref(false);
const expeditingSign = async () => {
  urgeSignLoading.value = true;
  try {
    await urgeSign({
      businessId: taskInfo.value.taskId,
    });
    uni.showToast({
      title: '催签成功',
      icon: 'none',
      duration: 2000,
    });
    urgeSignLoading.value = false;
  } catch {
    urgeSignLoading.value = false;
  }
};

const taskInfo: any = ref({ status: 1 });
const loading = ref(true);
const formList = ref<any[]>([]);
const reloadInfo = (applyId: string) => {
  loading.value = true;
  queryProjectApplyDetail({ applyId }).then((res: any) => {
    taskInfo.value = res;
    if (res?.formList && res?.formList.length) {
      list.value = res.formList.map((item: any) => {
        return {
          name: item.formName,
        };
      });
      list.value.push({
        name: '文件信息',
      });
    }
    if (
      tab.value === 'filelist' &&
      list.value.some((item) => item.name === '文件信息')
    ) {
      current.value = list.value.findIndex((item) => item.name === '文件信息');
      swiperCurrent.value = list.value.findIndex(
        (item) => item.name === '文件信息'
      );
    }
    loading.value = false;
  });
};
const refFileList = ref();
function socketInit(res: any) {
  console.log(res, 'socket info');
  if (res.businessType === 13) {
    refFileList.value[0]?.reloadData();
  }
  if (res.businessType === 14) {
    reloadInfo(taskId.value);
    refFileList.value[0]?.reloadData();
  }
}
function offSocketInfo() {
  console.log('off socket');
  uni.$off('socket_message', socketInit);
}
onMounted(() => {
  console.log('on socket');
  uni.$on('socket_message', socketInit);
});
onUnmounted(() => {
  offSocketInfo();
});

useBack(() => {
  if (uni.getStorageSync('toFileList') === '1') {
    if (list.value.some((item) => item.name === '文件信息')) {
      current.value = list.value.findIndex((item) => item.name === '文件信息');
      swiperCurrent.value = list.value.findIndex(
        (item) => item.name === '文件信息'
      );
      uni.removeStorageSync('toFileList');
    }
  } else {
    reloadInfo(taskId.value);
  }
});
const taskId = ref<any>({});
const projectInfo = ref<any>({});
const tab = ref<string>('');
onLoad(() => {
  const { taskId: tId, label, tab: _tab } = (uni as any).$Router.getQuery();
  tab.value = _tab;
  uni.setNavigationBarTitle({
    title: label,
  });
  taskId.value = tId;
  reloadInfo(taskId.value);
});
</script>
<style lang="scss">
.swiper {
  height: calc(100vh - 200rpx - env(safe-area-inset-bottom));
  .content-page {
    height: calc(100vh - 224rpx - env(safe-area-inset-bottom));
  }
  &.noButton {
    height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
    .content-page {
      height: calc(100vh - 124rpx - env(safe-area-inset-bottom));
    }
  }
}
.btn-box {
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  z-index: 10;
}
.transition-bg {
  width: 90%;
  // height: 400rpx;
  border-radius: 30rpx;
  padding: 20rpx;
  margin: 0 auto;
  margin-top: 20rpx;
  background: linear-gradient(to top, #d6e9ff, #fff);

  .project-name {
    font-size: 32rpx;
    height: auto;
    font-weight: bold;
  }
  .tag-box {
    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;
    align-items: center;

    .tag-item {
      background: rgba(255, 255, 255, 0.5);
      padding: 5rpx 10rpx;
      border-radius: 10rpx;
      font-size: 24rpx;
      color: #0177fd;
    }
    .m-x-10 {
      margin: 0 10rpx;
    }
  }
}
</style>
